'use strict';

const semver = require('semver')

function getNpmInfo(npmName, registry) {
    if (!npmName) {
        return null
    } else {
        const urlJoin = require('url-join')
        const axios = require('axios')
        const registryUrl = registry || getDefaultRegistry()
        const npmInfoUrl =  urlJoin(registryUrl, npmName)
        return axios.get(npmInfoUrl).then(res => {
            if (res.status === 200) {
                return res.data
            }
            return null
        }).catch(err => {
            return  Promise.reject(err)
        })
    }
}

async function getLatestNpmVersions(npmName, registry) {
    const versions = await getNpmVersions(npmName, registry)
    const newVersions = getSemverVersions(versions)
    if (newVersions && newVersions.length > 0) {
        return newVersions[0]
    }
    return null
}

function getSemverVersions(versions) {
    versions.sort((a, b) => semver.gt(b, a) ? 1 : -1)
    return versions
}

async function getNpmVersions(npmName, registry) {
    const data = await getNpmInfo(npmName, registry)
    if (data) {
        return Object.keys(data.versions)
    } else {
        return []
    }
}

function getDefaultRegistry(isOriginal = false) {
    return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getSemverVersions,
    getLatestNpmVersions,
    getDefaultRegistry
}

